package org.mat.ipaas.ucenter.service.modules.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.system.query.QueryGenerator;
import org.mat.ipaas.ucenter.biz.common.util.oConvertUtils;
import org.mat.ipaas.ucenter.biz.modules.system.entity.SysLog;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysLogService;
import org.mat.ipaas.ucenter.service.api.system.SysLogRestAPI;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysLogDTO;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysRoleDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 系统日志表 前端控制器
 * </p>
 *
 * @Author zhangweijian
 * @since 2018-12-26
 */
@RestController
@RequestMapping("/sys/log")
@Slf4j
public class SysLogController implements SysLogRestAPI {
	
	@Autowired
	private ISysLogService sysLogService;

    /**
     * 全部清除
     */
	private static final String ALL_ClEAR = "allclear";

	/**
	 * @功能：查询日志记录
	 * @param sysLogDTO
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public MatApiResponse<Page<SysLogDTO>> queryPageList(@SpringQueryMap SysLogDTO sysLogDTO,
														  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest req = attributes.getRequest();

		MatApiResponse<Page<SysLogDTO>> matApiResponse = new MatApiResponse<>();
		SysLog sysLog = toSysLog(sysLogDTO);

		QueryWrapper<SysLog> queryWrapper = QueryGenerator.initQueryWrapper(sysLog, req.getParameterMap());
		Page<SysLog> page = new Page<SysLog>(pageNo, pageSize);
		//日志关键词
		String keyWord = req.getParameter("keyWord");
		if(oConvertUtils.isNotEmpty(keyWord)) {
			queryWrapper.like("log_content",keyWord);
		}
		//TODO 过滤逻辑处理
		//TODO begin、end逻辑处理
		//TODO 一个强大的功能，前端传一个字段字符串，后台只返回这些字符串对应的字段
		//创建时间/创建人的赋值
		IPage<SysLog> pageList = sysLogService.page(page, queryWrapper);
		log.info("查询当前页："+pageList.getCurrent());
		log.info("查询当前页数量："+pageList.getSize());
		log.info("查询结果数量："+pageList.getRecords().size());
		log.info("数据总数："+pageList.getTotal());
		matApiResponse.setSuccess(true);
		matApiResponse.setData(toSysLogDTOPage(pageList));
		return matApiResponse;
	}

	/**
	 * @功能：删除单个日志记录
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
	public MatApiResponse<SysLogDTO> delete(@RequestParam(name="id",required=true) String id) {
		MatApiResponse<SysLogDTO> matApiResponse = new MatApiResponse<>();
		SysLog sysLog = sysLogService.getById(id);
		if(sysLog==null) {
			matApiResponse.fail("未找到对应实体");
		}else {
			boolean ok = sysLogService.removeById(id);
			if(ok) {
				matApiResponse.success("删除成功!");
			}
		}
		return matApiResponse;
	}
	
	/**
	 * @功能：批量，全部清空日志记录
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
	public MatApiResponse<SysRoleDTO> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		MatApiResponse<SysRoleDTO> matApiResponse = new MatApiResponse<>();
		if(ids==null || "".equals(ids.trim())) {
			matApiResponse.fail("参数不识别！");
		}else {
			if(ALL_ClEAR.equals(ids)) {
				this.sysLogService.removeAll();
				matApiResponse.success("清除成功!");
			}
			this.sysLogService.removeByIds(Arrays.asList(ids.split(",")));
			matApiResponse.success("删除成功!");
		}
		return matApiResponse;
	}



	private Page<SysLogDTO> toSysLogDTOPage(IPage<SysLog> pageList) {
		Page<SysLogDTO> sysLogDTOPage = new Page<>();
		List<SysLogDTO> sysLogDTOList = new ArrayList<>();
		if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())){
			for (SysLog sysLog : pageList.getRecords()) {
				sysLogDTOList.add(toSysLogDTO(sysLog));
			}
		}

		sysLogDTOPage.setTotal(pageList.getTotal());
		sysLogDTOPage.setSize(pageList.getSize());
		sysLogDTOPage.setCurrent(pageList.getCurrent());
		sysLogDTOPage.setRecords(sysLogDTOList);

		return sysLogDTOPage;
	}

	private SysLogDTO toSysLogDTO(SysLog sysLog) {
		if (sysLog == null) {
			return null;
		}
		SysLogDTO sysLogDTO = new SysLogDTO();
		sysLogDTO.setId(sysLog.getId());
		sysLogDTO.setCreateBy(sysLog.getCreateBy());
		sysLogDTO.setCreateTime(sysLog.getCreateTime());
		sysLogDTO.setUpdateBy(sysLog.getUpdateBy());
		sysLogDTO.setUpdateTime(sysLog.getUpdateTime());
		sysLogDTO.setCostTime(sysLog.getCostTime());
		sysLogDTO.setIp(sysLog.getIp());
		sysLogDTO.setRequestParam(sysLog.getRequestParam());
		sysLogDTO.setRequestType(sysLog.getRequestType());
		sysLogDTO.setRequestUrl(sysLog.getRequestUrl());
		sysLogDTO.setMethod(sysLog.getMethod());
		sysLogDTO.setUsername(sysLog.getUsername());
		sysLogDTO.setUserid(sysLog.getUserid());
		sysLogDTO.setLogContent(sysLog.getLogContent());
		sysLogDTO.setLogType(sysLog.getLogType());
		sysLogDTO.setOperateType(sysLog.getOperateType());
		sysLogDTO.setTenantId(sysLog.getTenantId());
		return sysLogDTO;
	}

	private SysLog toSysLog(SysLogDTO sysLogDTO) {
		if (sysLogDTO == null) {
			return null;
		}
		SysLog sysLog = new SysLog();
		sysLog.setId(sysLogDTO.getId());
		sysLog.setCreateBy(sysLogDTO.getCreateBy());
		sysLog.setCreateTime(sysLogDTO.getCreateTime());
		sysLog.setUpdateBy(sysLogDTO.getUpdateBy());
		sysLog.setUpdateTime(sysLogDTO.getUpdateTime());
		sysLog.setCostTime(sysLogDTO.getCostTime());
		sysLog.setIp(sysLogDTO.getIp());
		sysLog.setRequestParam(sysLogDTO.getRequestParam());
		sysLog.setRequestType(sysLogDTO.getRequestType());
		sysLog.setRequestUrl(sysLogDTO.getRequestUrl());
		sysLog.setMethod(sysLogDTO.getMethod());
		sysLog.setUsername(sysLogDTO.getUsername());
		sysLog.setUserid(sysLogDTO.getUserid());
		sysLog.setLogContent(sysLogDTO.getLogContent());
		sysLog.setLogType(sysLogDTO.getLogType());
		sysLog.setOperateType(sysLogDTO.getOperateType());
		sysLog.setTenantId(sysLogDTO.getTenantId());
		return sysLog;
	}


}
